<template>
  <view class="tail-setting-container">
    <view class="header">
      <view class="back-btn" @click="goBack">
        <FeatherIcon name="chevron-left" size="24" color="#333" />
      </view>
      <text class="title">小尾巴设置</text>
      <view class="placeholder"></view>
    </view>

    <view class="form-container">
      <view class="form-item">
        <text class="label">开启小尾巴</text>
        <switch :checked="enableTail" @change="toggleTail" color="#007AFF" />
      </view>

      <view class="form-item options" v-if="enableTail">
        <text class="label">小尾巴选项</text>
      </view>

      <view class="option-list" v-if="enableTail">
        <!-- 自定义输入 -->
        <view class="option-item" @click="selectOption('custom')">
          <view class="option-left">
            <view
              class="radio"
              :class="{ 'radio-active': tailOption === 'custom' }"
            ></view>
            <text class="option-text">自定义内容</text>
          </view>
        </view>

        <!-- 用户活跃度 -->
        <view class="option-item" @click="selectOption('active')">
          <view class="option-left">
            <view
              class="radio"
              :class="{ 'radio-active': tailOption === 'active' }"
            ></view>
            <text class="option-text">显示活跃度</text>
          </view>
          <text class="option-desc" v-if="tailOption === 'active' && userActive"
            >活跃度: {{ userActive }}</text
          >
        </view>

        <!-- 每日一句 -->
        <view class="option-item" @click="selectOption('quote')">
          <view class="option-left">
            <view
              class="radio"
              :class="{ 'radio-active': tailOption === 'quote' }"
            ></view>
            <text class="option-text">每日一句</text>
          </view>
          <text
            class="option-desc"
            v-if="tailOption === 'quote' && dailyQuote"
            >{{ dailyQuote }}</text
          >
        </view>
      </view>

      <view
        class="input-container"
        v-if="enableTail && tailOption === 'custom'"
      >
        <textarea
          class="tail-input"
          v-model="tailContent"
          placeholder="请输入你的小尾巴内容，例如：来自摸鱼派客户端"
          :maxlength="100"
          auto-height
        />
        <text class="counter">{{ tailContent.length }}/100</text>
      </view>

      <view class="preview" v-if="enableTail && getPreviewContent()">
        <text class="preview-title">预览效果</text>
        <view class="preview-content">
          <text class="message-text">这是一条消息</text>
          <text class="tail-text">{{ getPreviewContent() }}</text>
        </view>
      </view>

      <view class="tips" v-if="enableTail">
        <text class="tips-title">提示：</text>
        <text class="tips-content"
          >小尾巴会自动添加到你的每条消息末尾，建议使用简短文字。</text
        >
      </view>

      <button class="save-btn" @click="saveTailSettings">保存设置</button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from "vue";
import FeatherIcon from "@/components/FeatherIcon.vue";
import { showSuccess } from "@/utils/common.js";
import { userApi } from "@/api/modules/user.js";

// 状态变量
const enableTail = ref(false);
const tailContent = ref("");
const tailOption = ref("custom"); // 'custom', 'active', 'quote'
const userActive = ref("");
const dailyQuote = ref("");
const isLoading = ref(false);

// 页面加载时读取设置
onMounted(() => {
  loadTailSettings();
  if (tailOption.value === "active") {
    fetchUserActive();
  } else if (tailOption.value === "quote") {
    fetchDailyQuote();
  }
});

// 加载已保存的设置
const loadTailSettings = () => {
  try {
    const settings = uni.getStorageSync("chatTailSettings");
    if (settings) {
      const parsedSettings = JSON.parse(settings);
      enableTail.value = parsedSettings.enableTail || false;
      tailContent.value = parsedSettings.tailContent || "";
      tailOption.value = parsedSettings.tailOption || "custom";
    }
  } catch (e) {
    console.error("读取小尾巴设置失败", e);
  }
};

// 切换开关状态
const toggleTail = (e) => {
  enableTail.value = e.detail.value;
};

// 选择小尾巴选项
const selectOption = (option) => {
  tailOption.value = option;

  if (option === "active" && !userActive.value) {
    fetchUserActive();
  } else if (option === "quote" && !dailyQuote.value) {
    fetchDailyQuote();
  }
};

// 获取用户活跃度
const fetchUserActive = async () => {
  try {
    isLoading.value = true;
    const res = await userApi.getActive();
    if (res) {
      userActive.value = res.liveness || "暂无活跃度数据";
    } else {
      userActive.value = "获取活跃度失败";
    }
  } catch (e) {
    console.error("获取活跃度失败", e);
    userActive.value = "获取活跃度失败";
  } finally {
    isLoading.value = false;
  }
};

// 获取每日一句
const fetchDailyQuote = async () => {
  try {
    isLoading.value = true;
    const quote = await userApi.getOneQuote();
    dailyQuote.value = quote || "暂无每日一句数据";
  } catch (e) {
    console.error("获取每日一句失败", e);
    dailyQuote.value = "获取每日一句失败";
  } finally {
    isLoading.value = false;
  }
};

// 获取预览内容
const getPreviewContent = () => {
  if (tailOption.value === "custom") {
    return tailContent.value;
  } else if (tailOption.value === "active" && userActive.value) {
    return `活跃度: ${userActive.value}`;
  } else if (tailOption.value === "quote" && dailyQuote.value) {
    return dailyQuote.value;
  }
  return "";
};

// 保存设置
const saveTailSettings = () => {
  try {
    // 获取要保存的小尾巴内容
    let finalTailContent = "";
    if (tailOption.value === "custom") {
      finalTailContent = tailContent.value;
    } else if (tailOption.value === "active") {
      finalTailContent = `活跃度: ${userActive.value}`;
    } else if (tailOption.value === "quote") {
      finalTailContent = dailyQuote.value;
    }

    // 保存到本地存储
    const settings = {
      enableTail: enableTail.value,
      tailContent: finalTailContent,
      tailOption: tailOption.value,
    };

    uni.setStorageSync("chatTailSettings", JSON.stringify(settings));
    showSuccess("设置已保存");

    // 延迟返回上一页
    setTimeout(() => {
      goBack();
    }, 1000);
  } catch (e) {
    console.error("保存小尾巴设置失败", e);
    uni.showToast({
      title: "保存失败，请重试",
      icon: "none",
    });
  }
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};
</script>

<style lang="scss">
.tail-setting-container {
  min-height: 100vh;
  background-color: #f7f7f7;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  padding-top: 60rpx;
  background-color: #fff;
  position: relative;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);

  .back-btn {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }

  .placeholder {
    width: 60rpx;
  }
}

.form-container {
  padding: 30rpx;
}

.form-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  background-color: #fff;
  border-radius: 12rpx;
  margin-bottom: 20rpx;

  .label {
    font-size: 28rpx;
    color: #333;
    font-weight: 500;
  }

  &.options {
    margin-bottom: 0;
    border-bottom-left-radius: 0;
    border-bottom-right-radius: 0;
  }
}

.option-list {
  background-color: #fff;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  border-top-left-radius: 0;
  border-top-right-radius: 0;
  overflow: hidden;

  .option-item {
    padding: 25rpx 30rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-top: 1px solid #f5f5f5;

    .option-left {
      display: flex;
      align-items: center;
    }

    .radio {
      width: 36rpx;
      height: 36rpx;
      border-radius: 50%;
      border: 2rpx solid #999;
      margin-right: 20rpx;
      position: relative;

      &.radio-active {
        border-color: #007aff;

        &:after {
          content: "";
          position: absolute;
          width: 20rpx;
          height: 20rpx;
          border-radius: 50%;
          background-color: #007aff;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
        }
      }
    }

    .option-text {
      font-size: 28rpx;
      color: #333;
    }

    .option-desc {
      font-size: 24rpx;
      color: #999;
      max-width: 60%;
      text-align: right;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
}

.input-container {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 20rpx 30rpx;
  margin-bottom: 20rpx;
  position: relative;

  .tail-input {
    width: 100%;
    font-size: 28rpx;
    min-height: 120rpx;
    line-height: 1.5;
    color: #333;
  }

  .counter {
    position: absolute;
    bottom: 20rpx;
    right: 30rpx;
    font-size: 24rpx;
    color: #999;
  }
}

.preview {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 20rpx 30rpx;
  margin-bottom: 20rpx;

  .preview-title {
    font-size: 26rpx;
    color: #666;
    margin-bottom: 16rpx;
    display: block;
  }

  .preview-content {
    background-color: #f5f7fa;
    padding: 20rpx;
    border-radius: 8rpx;

    .message-text {
      font-size: 28rpx;
      color: #333;
      display: block;
      margin-bottom: 10rpx;
    }

    .tail-text {
      font-size: 24rpx;
      color: #999;
      display: block;
      padding-top: 10rpx;
      border-top: 1px dashed #e0e0e0;
    }
  }
}

.tips {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 20rpx 30rpx;
  margin-bottom: 40rpx;

  .tips-title {
    font-size: 26rpx;
    color: #ff8c00;
    font-weight: 500;
  }

  .tips-content {
    font-size: 26rpx;
    color: #666;
    line-height: 1.5;
  }
}

.save-btn {
  background-color: #007aff;
  color: #fff;
  font-size: 30rpx;
  height: 90rpx;
  line-height: 90rpx;
  border-radius: 45rpx;
  margin-top: 60rpx;

  &:active {
    opacity: 0.8;
  }
}
</style>
